<script setup>
import { ref,reactive, nextTick,onActivated,getCurrentInstance,onMounted, watch  } from 'vue'; 
import { useRoute,useRouter } from 'vue-router';
import EditDialog from './components/EditDialog.vue'
import { paymentBusinessList,PaymentSerDisable,editPayService} from '@/api/OperationManage/index.js'
import { useDistInfoStore } from '@/stores/dict.js'
const distInfoStore = useDistInfoStore();
const seachTable = ref(null);
const route = useRoute();
const router = useRouter();
const instance = getCurrentInstance();

// dialog弹框组件

const dialogVisible = ref(false)
// 弹框文字
const dialogTitle = ref('')
const handleClose = () => {
    cancel()
}
const backForm = ref({
  channel:1,
  storeName:'',//门店名称
  licenseName:'',//营业执照名称
  channelNo:'',
  merchantCode:''
})


// 经营品牌数据
const operBrandList = computed(()=>{
    return distInfoStore.getDistInfos("经营品牌").map(lis=>{
        return {
            value:lis.id,
            label:lis.permissionName
        }
    })
})

// 门店分组列表 
const storeList = computed(()=>{
    return distInfoStore.getDistInfos("门店分组").map(lis=>{
        return {
            value:lis.id,
            label:lis.permissionName
        }
    })
})

const changeDialog = (val) => {
    dialogVisible.value = val
}


// 启用禁用switch选择
const changeStatue = (val,row) => {
  ElMessageBox({
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          title: '禁用',
          showCancelButton: true,
          message:val ? "确定要启用吗?" : '确定要禁用吗',
          beforeClose: async (action, instance, done) => {
              if (action === 'confirm') {
                  instance.confirmButtonLoading = true
                  instance.confirmButtonText = 'Loading...'
                  // ElMessage.success('禁用成功');
                  try {
                    let params = {
                      id:row.id,
                      status:val ? 1 : 0
                    }
                    const result = await PaymentSerDisable(params)
                    ElMessage({
                      type: 'success',
                      message: val ? '启用成功' : '禁用成功' 
                    }) 
                    seachTable.value.handlerSearch(); 

                  } catch (error) {
                  }finally{
                    instance.confirmButtonLoading = false
                    done() 
                  }
                   
              } else {
                seachTable.value.handlerSearch(); 
                  done()
              }
          },
              }
          )
  console.log(val,'val');
  console.log(row,'row');
}



const submitPay = async (val) => {
  // console.log(val,'val');
  try {
    const res = await editPayService(val)
    dialogVisible.value = false
    ElMessage.success('编辑成功')
    seachTable.value.handlerSearch();
  } catch (error) {
    
  }
  

}
// 新增编辑回退时候刷新列表
onActivated(()=>{

    let closeTagName = sessionStorage.getItem('closeTagName');
    if(closeTagName == 'pharmacistManageEdit'){
        seachTable.value.handlerSearch();
        
    }else if(closeTagName == 'pharmacistManageAdd'){
        seachTable.value.initSearch();
    }
    instance.proxy.$forceUpdate();
    sessionStorage.removeItem('closeTagName');
})

// 表格控件
const formInline = ref([
    {
      type: "datePicker",
      prop: ["beginTime", "endTime"],
      startPlaceholder: "创建开始时间",
      endPlaceholder: "创建结束时间",
      label: "",
      model: [],
    },
    {
      type: "input",
      prop: "keywords",
      placeholder: "门店名称/ID",
      label: "",
      model: "",
    },
    {
      type: "input",
      prop: "enterpriseName",
      placeholder: "所属商户",
      label: "",
      model: "",
    },
    {
        type: "select",
        placeholder: "经营方式",
        label: '',
        prop: 'managementWays',
        multiple:true,
        data:[
            {
                label:"直营",
                value:1
            },
            {
              
                label:"加盟",
                value:2
            }
        ],
        model: [],
    },
    {
        type: "select",
        placeholder: "经营品牌",
        label: '',
        prop: 'brandIds',
        multiple:true,
        data:operBrandList.value,
        model:[]
    },
    {
        type: "select",
        placeholder: "门店分组",
        label: '',
        prop: 'storeGroupIds',
        multiple:true,
        data:storeList.value,
        model:[]
    },
    {
      type: "input",
      prop: "address",
      placeholder: "所属地区",
      label: "",
      model: "",
    },
    // {
    //   type: "input",
    //   prop: "mobile",
    //   placeholder: "到期天数",
    //   label: "",
    //   model: "",
    // },
])

const btnLefts = ref([

])
const btnRights = ref([

])

const tableConfig = ref([
    {
      prop: "code",
      label: "门店ID",
      width:200
    },
    {
      prop: "licenseName",
      label: "营业执照名称",
      width:200
    },
    {
      prop: "storeName",
      label: "门店名称",
      width:200
    },

    {
      prop:'status',
      label:'状态',
      type:'slot',
      slotName:'statusName'
    },
    // {
    //   prop: "institutions",
    //   label: "到期天数",
    //   width:200
    // },
    {
      prop: "enterpriseName",
      label: "所属商户",
      width:200
    },
    {
      prop: "managementWay",
      label: "经营方式",
      width:200,
      format:(val) => {
        return  val == 1 ? '直营' : '加盟'
      }
    },
    {
      prop: "brandId",
      label: "经营品牌",
      width:200,
      format:(val) => {
        if(val){
          let newArray = val.split(',')
          let matches = []
          for (const valueToMatch of newArray) {
              const matchingItem = operBrandList.value.find(item => item.value === valueToMatch);
              if (matchingItem) { 
                  matches.push(matchingItem.label);
              }
            }
          return matches.join(",");
        }else{
          return '-'
        }
      }
    },
    {
      prop: "addr",
      label: "所属地区",
      width:200
    },
    {
      prop: "storeGroupId",
      label: "门店分组",
      width:100,
      format:(val) => {
        if(val){
          let newArray = val.split(',')
          let matches = []
          for (const valueToMatch of newArray) {
              const matchingItem = storeList.value.find(item => item.value === valueToMatch);
              if (matchingItem) { 
                  matches.push(matchingItem.label);
              }
            }
          return matches.join(",");
        }else{
          return '-'
        }
      }
    },
    {
      prop: "linkman",
      label: "联系人",

    },
    {
      prop: "phone",
      label: "手机号码",
      width:150
    },
    {
      prop: "creator",
      label: "创建人",
    },
    {
      prop: "createTime",
      label: "创建时间",
      width:200
    },
    {
      type: "action",
      label: "操作",
      width: 100,
      btns: [
        {
          label: () => "编辑",
          type:"success",
          show:(row)=>{
            return true;
          },
          click: async (row) => {
            // console.log(row,'row');
            backForm.value = {
                id:row.id || '',
                channel:1,
                storeName: row.storeName || '',//门店名称
                licenseName: row.licenseName || '',//营业执照名称
                channelNo: row.channelNo ||'',
                merchantCode: row.merchantCode || ''
              }

            dialogTitle.value = '编辑'
            dialogVisible.value = true
          },
        }
      ],  
    },
]);
const tableLoading = ref(false)
const totalPage = ref(0)
const tableData = ref([]);


const handlerSearch = async (formInline)=>{
  console.log(formInline,'llllll');
    tableLoading.value = true;
    try{
        const res = await paymentBusinessList(formInline)
        console.log(res,'res');
        totalPage.value = res.total;
        tableData.value = res.records.map(value=>{
          return {
            ...value,
            status:value.status == 1 ? true: false
          }
        })
        tableLoading.value = false;
    }catch(e){
        tableLoading.value = false;
    }
}



</script>
<template>
    <div class="page-content">
        <SeachTable 
          :tableType="1"
          ref="seachTable"
          :forms="formInline"
          :btnLefts="btnLefts"
          :btnRights="btnRights"
          :tableLoading="tableLoading"
          :tableConfig="tableConfig"
          :tableData="tableData"
          :totalPage="totalPage"
          tableHeight="calc(100% - 202px)"
          @handlerSearch="handlerSearch"
        >
        <template #statusName={row}>
            <el-switch v-model="row.status" @change="(val) => changeStatue(val,row)"/>
          </template>
        </SeachTable>
        <edit-dialog
        v-if="dialogVisible"
        :dialogTitle="dialogTitle"
        :dialogVisible="dialogVisible"
        :backForm="backForm"
        @changeDialog="changeDialog"
        @submitPay="submitPay"
        ></edit-dialog>
                </div>
            </template>

<style lang="less" scoped>
   
   
</style>